package hu.dobrosi.j2me.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class HttpURLConnection {
	private Hashtable properties = new Hashtable();

	private StreamConnection connection;

	private String method = "GET";

	private OutputStream outputStream;

	private URL url;

	private InputStream inputStream;

	public HttpURLConnection() {
		super();
	}

	public HttpURLConnection(URL url) throws IOException, MalformedURLException {
		this.url = url;
	}

	public void setRequestProperty(String p, String v) {
		properties.put(p, v);
	}

	public void setRequestMethod(String m) throws IOException {
		method = m;
	}

	public void setDoOutput(boolean b) throws IOException {
	}

	public void setDoInput(boolean b) throws IOException {
	}

	public void connect() throws IOException {
		String urlString = "socket://" + url.getHost() + ":" + url.getPort();
		connection = (StreamConnection) Connector.open(urlString);
		outputStream = connection.openOutputStream();
		String line = method + " " + url.getPage() + " HTTP/1.0\n";
		outputStream.write(line.getBytes());
		Enumeration propKeys = properties.keys();
		while (propKeys.hasMoreElements()) {
			Object key = propKeys.nextElement();
			line = key + ": " + properties.get(key) + "\n";
			outputStream.write(line.getBytes());
			outputStream.flush();

		}
		outputStream.write("\n".getBytes());
		outputStream.flush();
	}

	public OutputStream getOutputStream() throws IOException {
		return outputStream;
	}

	public InputStream getInputStream() throws IOException {
		outputStream.close();
		inputStream = connection.openInputStream();
		if (inputStream.available() == 0)
			while (inputStream.read() == -1)
				;
		return inputStream;
	}

	public void close() throws IOException {
		outputStream.close();
		inputStream.close();
		connection.close();
	}
}
